'use client'

import { useState, useEffect } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { ArrowLeft, Users, FolderOpen, CheckSquare, Bug, Calendar, Activity } from 'lucide-react'

interface ProjectDetail {
  id: string
  name: string
  key: string
  description?: string
  type: string
  status: string
  createdAt: string
  updatedAt: string
  _count: {
    requirements: number
    tasks: number
    bugs: number
    members: number
  }
}

export function ProjectDetailSimple() {
  const params = useParams()
  const router = useRouter()
  const projectId = params.id as string
  const [project, setProject] = useState<ProjectDetail | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (projectId) {
      fetchProjectDetail()
    }
  }, [projectId])

  const fetchProjectDetail = async () => {
    setLoading(true)
    setError(null)
    try {
      const response = await fetch(`/api/projects/${projectId}`)
      if (response.ok) {
        const data = await response.json()
        setProject(data)
      } else {
        const errorData = await response.json()
        setError(errorData.error || 'Failed to fetch project')
      }
    } catch (error) {
      console.error('Error fetching project detail:', error)
      setError('Network error')
    } finally {
      setLoading(false)
    }
  }

  const getStatusColor = (status: string) => {
    const colors: Record<string, string> = {
      ACTIVE: 'bg-green-100 text-green-800',
      ARCHIVED: 'bg-gray-100 text-gray-800',
      COMPLETED: 'bg-blue-100 text-blue-800'
    }
    return colors[status] || 'bg-gray-100 text-gray-800'
  }

  const getTypeColor = (type: string) => {
    const colors: Record<string, string> = {
      SOFTWARE: 'bg-purple-100 text-purple-800',
      HARDWARE: 'bg-orange-100 text-orange-800',
      INTEGRATED: 'bg-blue-100 text-blue-800',
      MATERIAL: 'bg-yellow-100 text-yellow-800'
    }
    return colors[type] || 'bg-gray-100 text-gray-800'
  }

  const getTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      SOFTWARE: '软件项目',
      HARDWARE: '硬件项目',
      INTEGRATED: '集成项目',
      MATERIAL: '物料项目'
    }
    return labels[type] || type
  }

  const getStatusLabel = (status: string) => {
    const labels: Record<string, string> = {
      ACTIVE: '活跃',
      ARCHIVED: '已归档',
      COMPLETED: '已完成'
    }
    return labels[status] || status
  }

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center space-x-4">
          <Button variant="ghost" size="icon">
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <Skeleton className="h-8 w-48 mb-2" />
            <Skeleton className="h-4 w-64" />
          </div>
        </div>
        
        <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
          {[1, 2, 3, 4].map((i) => (
            <Card key={i}>
              <CardHeader className="pb-2">
                <Skeleton className="h-4 w-20" />
              </CardHeader>
              <CardContent>
                <Skeleton className="h-8 w-12" />
              </CardContent>
            </Card>
          ))}
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="text-center py-12">
        <h3 className="text-lg font-medium text-gray-900 mb-2">加载失败</h3>
        <p className="text-gray-500 mb-4">{error}</p>
        <Button onClick={() => router.push('/projects')}>
          <ArrowLeft className="h-4 w-4 mr-2" />
          返回项目列表
        </Button>
      </div>
    )
  }

  if (!project) {
    return (
      <div className="text-center py-12">
        <h3 className="text-lg font-medium text-gray-900 mb-2">项目未找到</h3>
        <p className="text-gray-500 mb-4">请检查项目ID是否正确</p>
        <Button onClick={() => router.push('/projects')}>
          <ArrowLeft className="h-4 w-4 mr-2" />
          返回项目列表
        </Button>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 页面头部 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <Button variant="ghost" size="icon" onClick={() => router.push('/projects')}>
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <h1 className="text-3xl font-bold tracking-tight">{project.name}</h1>
            <div className="flex items-center space-x-2 mt-2">
              <Badge className={getTypeColor(project.type)}>
                {getTypeLabel(project.type)}
              </Badge>
              <Badge className={getStatusColor(project.status)}>
                {getStatusLabel(project.status)}
              </Badge>
              <span className="text-sm text-gray-500 font-mono bg-gray-100 px-2 py-1 rounded">
                {project.key}
              </span>
            </div>
            {project.description && (
              <p className="text-gray-600 mt-2">{project.description}</p>
            )}
          </div>
        </div>
      </div>

      {/* 统计卡片 */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">需求</CardTitle>
            <CheckSquare className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{project._count.requirements}</div>
            <p className="text-xs text-muted-foreground">
              功能需求和改进
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">任务</CardTitle>
            <Activity className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{project._count.tasks}</div>
            <p className="text-xs text-muted-foreground">
              工作任务和活动
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">缺陷</CardTitle>
            <Bug className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{project._count.bugs}</div>
            <p className="text-xs text-muted-foreground">
              缺陷和问题
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">团队成员</CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{project._count.members}</div>
            <p className="text-xs text-muted-foreground">
              项目成员
            </p>
          </CardContent>
        </Card>
      </div>

      {/* 项目信息 */}
      <Card>
        <CardHeader>
          <CardTitle>项目信息</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center justify-between">
            <span className="text-sm font-medium">项目标识</span>
            <span className="text-sm font-mono bg-gray-100 px-2 py-1 rounded">{project.key}</span>
          </div>
          <div className="flex items-center justify-between">
            <span className="text-sm font-medium">项目类型</span>
            <Badge className={getTypeColor(project.type)}>
              {getTypeLabel(project.type)}
            </Badge>
          </div>
          <div className="flex items-center justify-between">
            <span className="text-sm font-medium">项目状态</span>
            <Badge className={getStatusColor(project.status)}>
              {getStatusLabel(project.status)}
            </Badge>
          </div>
          <div className="flex items-center justify-between">
            <span className="text-sm font-medium">创建时间</span>
            <span className="text-sm text-gray-600">
              {new Date(project.createdAt).toLocaleDateString('zh-CN')}
            </span>
          </div>
          <div className="flex items-center justify-between">
            <span className="text-sm font-medium">更新时间</span>
            <span className="text-sm text-gray-600">
              {new Date(project.updatedAt).toLocaleDateString('zh-CN')}
            </span>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}